<?php
/**
 * Created by PhpStorm.
 * User: sunbo
 * Date: 2019/7/2
 * Time: 1:51 PM
 */
namespace app\index\controller;
use think\Exception;
class Login extends BaseContorller
{
    //后台web登录
    public function weblogin()
    {
         $phone=$this->param("phone");
         $pwd=$this->param("pwd");
         $result=$this->_checklogin($phone,$pwd);
         if(strlen($result)>0){
             return $this->json_data("",$result);
         }
        return   $this->json_data( $this->_login($phone,$pwd),"");
    }

    function _checklogin($phone,$pwd){

        $counts =  $this->db_select("select count(*) counts from  token_sys_user WHERE phone='".$phone."'");
        if($counts[0]["counts"]==0){
            return "当前用户不存在";
        }
        $counts =  $this->db_select("SELECT count(*) counts from token_sys_user WHERE phone='".$phone."' and pwd='".$pwd."'");
        if($counts[0]["counts"]==0){
            return "密码错误";
        }
        return "";
    }

    function  _login($phone,$pwd){
        $counts =  $this->db_select("SELECT guid,phone,pwd,IFNULL(countries_num,'') countries_num,IFNULL(citpay_phone,'') citpay_phone,token_sys_admin_role_guid from token_sys_user WHERE phone='".$phone."' and pwd='".$pwd."'");
        $token=$this->md5_token($phone,$pwd);
        $data=array("userid"=> $counts[0]["guid"],"pwd"=>$counts[0]["pwd"],"phone"=>$counts[0]["phone"],"token"=>$token,"countries_num"=>$counts[0]["countries_num"],"citpay_phone"=>$counts[0]["citpay_phone"],"roleguid"=>$counts[0]["token_sys_admin_role_guid"]);
        return $data;
    }


    /**
     *
     * @api {post} api/login/applogin  APP 登录
     * @apiDescription   APP 登录
     * @apiGroup login
     * @apiParam {string} phone 手机号
     * @apiParam {string} pwd  密码
     * @apiSuccess {string}  userid  用户ID
     * @apiSuccess {string}  pwd  密码
     * @apiSuccess {string}  phone  手机号
     * @apiSuccess {string}  token  token
     * @apiSuccess {string}  countries_num  区号
     * @apiSuccess {string}  citpay_phone  citpay用户
     * @apiVersion 1.0.1
     */
    public function applogin()
    {
        $phone=$this->param("phone");
        $pwd=$this->param("pwd");
        $result=$this->_appchecklogin($phone,$pwd);
        if(strlen($result)>0){
            return $this->json_data("",$result);
        }
        return   $this->json_data( $this->_login($phone,$pwd),"");
    }

    function _appchecklogin($phone,$pwd){

        $counts =  $this->db_select("select count(*) counts from  token_sys_user WHERE phone='".$phone."'");
        if($counts[0]["counts"]==0){
            return "当前用户不存在";
        }

        $counts =  $this->db_select("select count(*) counts from  token_sys_user WHERE phone='".$phone."' and issystem=1");
        if($counts[0]["counts"]>0){
            return "当前用户为后台用户,不能登录";
        }

        $counts =  $this->db_select("SELECT count(*) counts from token_sys_user WHERE phone='".$phone."' and pwd='".$pwd."'");
        if($counts[0]["counts"]==0){
            return "密码错误";
        }

        return "";
    }


    /**
     *
     * @api {post} api/login/app_CheckRegistered  APP注册检查
     * @apiDescription   APP注册检查
     * @apiGroup login
     * @apiParam {string} phone 手机号
     * @apiParam {string} parent_phone 推荐人手机号
     * @apiSuccess {string}  data  返回空字符表示成功
     * @apiVersion 1.0.1
     */
    public function  app_CheckRegistered(){
        $phone=$this->param("phone");
        $parent_phone=$this->param("parent_phone");
        if(strlen($phone)==0){
            return $this->json_data("","手机号不能为空");
        }
        $resutl="";
        if($this->IsExistPhone($phone)){
            $resutl="手机号已注册";
        }
        if(strlen($parent_phone)>0)
        {
            if(!$this->IsExistPhone($parent_phone)){
                $resutl="推荐人手机号不存在";
            }
        }
        return $this->json_data("",$resutl);
    }


    /**
     *
     * @api {post} api/login/get_zjm  获取助记码
     * @apiDescription   获取助记码
     * @apiGroup login
     * @apiSuccess {string}  data  json 12个助记码
     * @apiVersion 1.0.1
     */
    public  function  get_zjm(){
        $row=$this->db_select("select name FROM token_sys_zjm  ORDER BY RAND() LIMIT 12");
        $array=array();
        for ($x=0;$x<count($row);$x++)
        {
            $array[$x]=$row[$x]["name"];
        }
        return $this->json_data($array,"");
    }


    /**
     *
     * @api {post} api/login/Get_CountriesNum  获取区号
     * @apiDescription   获取区号
     * @apiGroup login
     * @apiSuccess {string} countriesName 国家名+区号
     * @apiSuccess {string} countriesNum 区号
     * @apiVersion 1.0.1
     */
    public function  Get_CountriesNum(){
        $dddd= file_get_contents(ROOT_PATH."country.json");
        $dddd= json_decode($dddd);
        for ($x=0;$x<count($dddd);$x++){
            $dddd[$x]->countriesName=$dddd[$x]->countriesName." ".$dddd[$x]->countriesNum;
        }
        return $this->json_data($dddd,"");
    }




    /**
     *
     * @api {post} api/login/app_Registered  APP 注册
     * @apiDescription   APP 注册
     * @apiGroup login
     * @apiParam {string} phone 手机号
     * @apiParam {string} countriesNum 区号
     * @apiParam {string} pwd  密码
     * @apiParam {string} transaction_pwd  交易密码
     * @apiParam {string} parent_phone  推荐人手机号
     * @apiParam {string} zjm_words  助记码
     * @apiVersion 1.0.1
     */
    public function  app_Registered(){
        $phone=$this->param("phone");
        $pwd=$this->param("pwd");
        $countriesNum=$this->param("countriesNum");
        $transaction_pwd=$this->param("transaction_pwd");
        $parentphone=$this->param("parent_phone");
        $zjm_words=$this->param("zjm_words");
        if($this->IsExistPhone($phone)){
            return $this->json_data("","手机号已存在");
        }
        $data=$this->_app_Registered($phone,$pwd,$transaction_pwd,$parentphone,$zjm_words,$countriesNum);
        if(strlen($data)>0){
            return $this->json_data("",$data);
        }
         $login= $this->_login($phone,$pwd);
        return $this->json_data($login,"");
    }


    function  _app_Registered($phone,$pwd,$transaction_pwd,$parentphone,$zjm_words,$countriesNum){
           try{
               $CitPay_new_mobile=$countriesNum.','.$phone;
               $citpay_api=new CitPayApi();
               if($citpay_api->accountcheck($CitPay_new_mobile)){
                   exception("CitPay手机号已存在");
                   return "";
               }

           $row= $this->db_select("select guid from token_sys_user where phone='".$parentphone."'");
           $parentguid= "";
           if(count($row)>0){
               $parentguid= $row[0]["guid"];
           }
           $uuid=$this->uuid();
           $level=$this->_getParentLevel($parentguid);
           $levelcount=$this->_getLevelCount($level);
           $array=array("insert into token_sys_user(guid,phone,pwd,parent_guid,transaction_pwd,issystem,zjm_words,level,levelcount,token_sys_role_guid,countries_num) VALUES ('".$uuid."','".$phone."','".$pwd."','".$parentguid."','".$transaction_pwd."',0,'".$zjm_words."','".$level."',".$levelcount.",'1','".$countriesNum."')");


           //插入余额表
           $row= $this->db_select("select value from token_sys_config where guid='1'");
           $datecount=$row[0]["value"];
           $array[]="insert into token_user_custom_coin_balance (guid,token_sys_user_guid,startdate,enddate,token_count) VALUES(UUID(),'".$uuid."',now(),date_add(now(), interval ".$datecount." day),0)";


               //注册CITYPAY 用户
               if($citpay_api->accountRegister($CitPay_new_mobile,$CitPay_new_mobile)){

                   $coinrow=$this->db_select("SELECT guid FROM token_sys_coin");
                   for($x=0;$x<count($coinrow);$x++){
                       $array[]=$this->set_address($uuid,$coinrow[$x]["guid"],$CitPay_new_mobile);
                   }

                   $array[]="update token_sys_user set countries_num='".$countriesNum."',citpay_phone='".$phone."' where guid='".$uuid."'";
                   $data=$this->db_exec($array);
                   //更新级别Level
                   $friend=new Friend();
                   $friend->OpenLevel($parentguid);
               }else{
                   exception("注册CITPAY用户失败");
               }

           return $data;
           }catch (Exception $ex){
               return $ex->getMessage();
           }
    }

    function _getLevelCount($level){
        if(strlen($level)==0){
            return 0;
        }
        $level=count(explode("|",$level));
        return $level;
    }
    function _getParentLevel($parentguid){
        if(strlen($parentguid)==0){
            return "";
        }
        $row=$this->db_select("select CASE IFNULL(level,'') WHEN '' THEN guid ELSE concat(IFNULL(level,''),'|',guid) END levelguid,IFNULL(level,'') level from token_sys_user where guid='".$parentguid."'");
        if(strlen($row[0]["level"])==0){
            return $parentguid;
        }
        return $row[0]["levelguid"];
    }

    function  set_address($userguid,$coinguid,$CitPay_new_mobile){
        $chain= new Blockchain();
        $address="";
        $begin_block_height=0;
        $latest_block_height=0;
        switch ($coinguid){
            case "1":
                $address=$chain->Get_BTC_USDT_Address($CitPay_new_mobile);
                break;
            case "3":
                $address=$chain->Get_BTC_USDT_Address($CitPay_new_mobile);
                break;
            case "2":
                $address=$chain->Get_Custom_Coin_Address();
                $begin_block_height=$chain->Get_Custom_Coin_Height();
                $latest_block_height=$begin_block_height;
                break;
            default:
                break;
        }
        return "INSERT into token_user_coin_address(guid,token_sys_user_guid,token_sys_coin_guid,address,begin_block_height,latest_block_height) VALUES(UUID(),'".$userguid."','".$coinguid."','".$address."',".$begin_block_height.",".$latest_block_height.")";
    }


     function  IsExistPhone($phone){
         $row= $this->db_select("select count(*) counts from token_sys_user where phone='".$phone."'");
         if($row[0]["counts"]>0){
             return true;
         }else{
             return false;
         }
    }



    /**
     *
     * @api {post} api/login/app_Registered  APP 注册
     * @apiDescription   APP 注册
     * @apiGroup login
     * @apiParam {string} phone 手机号
     * @apiParam {string} countriesNum 区号
     * @apiParam {string} pwd  密码
     * @apiParam {string} transaction_pwd  交易密码
     * @apiParam {string} parent_phone  推荐人手机号
     * @apiParam {string} zjm_words  助记码
     * @apiVersion 1.0.1
     */
    public function  AdminPwd(){
        $phone=$this->param("phone");
        $pwd=$this->param("pwd");
        $countriesNum=$this->param("countriesNum");
        $transaction_pwd=$this->param("transaction_pwd");
        $parentphone=$this->param("parent_phone");
        $zjm_words=$this->param("zjm_words");
        if($this->IsExistPhone($phone)){
            return $this->json_data("","手机号已存在");
        }
        $data=$this->_app_Registered($phone,$pwd,$transaction_pwd,$parentphone,$zjm_words,$countriesNum);
        if(strlen($data)>0){
            return $this->json_data("",$data);
        }
        $login= $this->_login($phone,$pwd);
        return $this->json_data($login,"");
    }



    /**
     *
     * @api {post} api/login/GetWebZJM  web_后台助记码
     * @apiDescription   web_后台助记码
     * @apiGroup login
     * @apiParam {string} phone 手机号  默认传admin
     * @apiSuccess {string} data 返回助记码数组
     * @apiVersion 1.0.1
     */
    public function  GetWebZJM(){
        try{
            $phone=$this->param("phone");
            $array= $this->_GetWebZJM($phone);
            return $this->json_data($array,"");
        }catch (exception $e){
            return $this->json_data("",$e->getMessage());
        }
    }

    public  function _GetWebZJM($phone){
        $row=$this->db_select("select ifnull(zjm_words,'')  zjm_words from  token_sys_user where phone ='".$phone."'");
        if(count($row)==0){
            exception("手机号不存在");
        }
        if($row[0]["zjm_words"]==""){
            exception("请使用默认登录密码，进行登录");
        }
        $array= explode(',',$row[0]["zjm_words"]);

        return $array;
    }

    /**
     *
     * @api {post} api/login/ModifyWebPwd  web_修改密码
     * @apiDescription   web_修改密码
     * @apiGroup login
     * @apiParam {string} phone 手机号  默认传admin
     * @apiParam {string} helpcode 助记码
     * @apiParam {string} pwd 密码
     * @apiSuccess {string} data  返回助记码数组
     * @apiVersion 1.0.1
     */
    public function ModifyWebPwd(){
        try{
            $phone=$this->param("phone");
            $helpcode=$this->param("helpcode");
            $pwd=$this->param("pwd");
            $this->_ModifyWebPwd($phone,$helpcode,$pwd);
            return $this->json_data("","");
        }catch (exception $e){
            return $this->json_data("",$e->getMessage());
        }
    }

    function _ModifyWebPwd($phone,$helpcode,$pwd){
       $row= $this->db_select("select count(*) counts from token_sys_user where phone='".$phone."' and ifnull(zjm_words,'')='".$helpcode."'");
       if($row[0]["counts"]==0){
           exception("助记码不正确");
       }
       $this->db_exec(array("update  token_sys_user set pwd='".$pwd."' where phone='".$phone."' and  ifnull(zjm_words,'')='".$helpcode."'"));
    }



}
